﻿using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Options;
using Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Code {
    public class CacheHelper {
        public IMemoryCache Cache { get; private set; }

        public CacheHelper() {
            Cache = new MemoryCache(Options.Create(new MemoryCacheOptions()));
        }

        public List<Area> GetAreaList() {
            var result = Cache.GetOrCreate<string>("Area", entry => {
                string dir = $@"{Directory.GetCurrentDirectory()}";
                FileHelper file = new FileHelper();
                var content = file.ReadTextAsync($@"{dir}\DB\data.json");

                return content.Result;
            });

            if ((result + "").Length > 0) {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<List<Area>>(result);
            }

            return null;
        }

        public List<Area> GetNewAreas() {
            var result = Cache.GetOrCreate<string>("NewAreas", entry => {
                string dir = $@"{Directory.GetCurrentDirectory()}";
                FileHelper file = new FileHelper();
                var content = file.ReadTextAsync($@"{dir}\DB\newData.json");

                return content.Result;
            });

            if ((result + "").Length > 0) {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<List<Area>>(result);
            }

            return null;
        }

        public List<Area> GetMenuList() {
            var result = Cache.GetOrCreate<string>("Menus", entry => {
                string dir = $@"{Directory.GetCurrentDirectory()}";
                FileHelper file = new FileHelper();
                var content = file.ReadTextAsync($@"{dir}\DB\menus.json");

                return content.Result;
            });

            if ((result + "").Length > 0) {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<List<Area>>(result);
            }

            return null;
        }
    }
}
